//
//  WYTabBar.swift
//  WYWeibo
//
//  Created by wangyi on 16/7/9.
//  Copyright © 2016年 wangyi. All rights reserved.
//

import UIKit

class WYTabBar: UITabBar {
    
    
    var composebuttonClosure: (() -> ())?
    
    //懒加载
    private lazy var composeButton: UIButton = {
    
        let button = UIButton()
        
        //点击事件
        button.addTarget(self, action: "composeButtonAction", forControlEvents: .TouchUpInside)
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        //适应性大小
        button.sizeToFit()
        return button
    }()
    
    //初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(composeButton)
    }
    //如果加载 XIb caihui 才会调用
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //点击事件
    @objc private func composeButtonAction() {
        
        
        print("hahaha")
        //实现 闭包
        composebuttonClosure?()
        
    }
    
    //坐标的计算
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        composeButton.center.x = frame.size.width * 0.5
        composeButton.center.y = frame.size.height * 0.5
        
        let itemWidth = frame.size.width / 5
        
        var index = 0
        
        for value in subviews {
        
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
            
                value.frame.origin.x = CGFloat(index) * itemWidth
                value.frame.size.width = itemWidth
                
                if index == 1 {
                    index++
                }
                index++
            
            }
        }
    }
}
